<template>
  <Card style="height:800px">
    <Row :gutter="12">
      <Col span="5">
      <Button type="text" style="font-family:'PingFang SC';font-weight:bold;font-size:16px;">组织机构</Button>
      <Tree :data="treeData" @on-select-change="handleSelectChange"></Tree>
      </Col>
      <Col span="19">
      <div v-if="this.subVue === 'view'">
        <Row>
          <Col>
          <Form ref="search" inline>
            <FormItem>
              <Input v-model="inUserCode" placeholder="用户名">
              </Input>
            </FormItem>
            <FormItem>
              <Button type="primary" icon="ios-search" @click="searchPage()"></Button>
              <Button @click="handleAdd" type="info" style="margin-left: 15px;">新建用户</Button>
            </FormItem>
          </Form>
          </Col>
        </Row>

        <Row>
          <Col>
          <Table :columns="columns1" :data="pageList.data" @on-sort-change="sortChange"></Table>
          <div style="margin: 10px;overflow: hidden">
            <div style="float: right;">
              <Page :total="pageList.dataTotal" :current="pageList.pageNum" :page-size="pageList.pageSize" @on-change="handlePageChange"></Page>
            </div>
          </div>
          </Col>
        </Row>
      </div>
      <div v-if="this.subVue === 'edit'">
        <Form ref="form" :model="form" :rules="rules" :label-width="80">
          <Row>
            <Col span="12">
            <FormItem label="用户名" prop="userCode">
              <Input v-model="form.userCode" placeholder="" :disabled="type===1||type===0">
              </Input>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="昵称" prop="userNamep">
              <Input v-model="form.userNamep" placeholder="" :disabled="type===0">
              </Input>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem label="姓名" prop="realName">
              <Input v-model="form.realName" placeholder="" :disabled="type===0">
              </Input>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="身份证号" prop="idCardNo">
              <Input v-model="form.idCardNo" placeholder="" :disabled="type===0">
              </Input>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem label="手机号码" prop="mobileNo">
              <Input v-model="form.mobileNo" placeholder="" :disabled="type===0">
              </Input>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="邮箱" prop="email">
              <Input v-model="form.email" placeholder="" :disabled="type===0">
              </Input>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem label="座机区号" prop="phoneZoneNo">
              <Input v-model="form.phoneZoneNo" placeholder="" :disabled="type===0">
              </Input>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="座机号" prop="shortPhoneNo">
              <Input v-model="form.shortPhoneNo" placeholder="" :disabled="type===0">
              </Input>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem label="入职日期" prop="entryDate">
              <DatePicker v-model="form.entryDate" :value="form.entryDate" type="date" placeholder="" :disabled="type===0"></DatePicker>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="离职日期" prop="leaveDate">
              <DatePicker v-model="form.leaveDate" :value="form.leaveDate" type="date" placeholder="" :disabled="type===0"></DatePicker>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem label="密码" prop="userPwd" v-if="type===2">
              <Input type="password" v-model="form.userPwd" placeholder="">
              </Input>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="确认密码" prop="confirmPwd" v-if="type===2">
              <Input type="password" v-model="form.confirmPwd" placeholder="">
              </Input>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem label="状态" prop="status">
              <Select v-model="form.status" :disabled="type===0">
                <Option v-for="item in selectStatus" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="岗位" prop="positionCode">
              <Input v-model="form.positionName" placeholder="" style="width:50%;margin:0px 10px 0px 0px" disabled  ></Input>
              <Button type="primary" @click="selectPosition" v-show="this.type===2">选择岗位</Button>
              <!-- <Button type="primary" @click="selectTraPosition" v-show="this.type===1">转岗位</Button> -->
            </FormItem>
            </Col>
          </Row>
          <FormItem label="角色：" prop="selectRoles">
            <CheckboxGroup v-model="selectRoles">
              <Checkbox v-for="role in roleList" :label='role.roleCode' :disabled="type===0" :key="role.id"><span>{{role.roleName}}</span></Checkbox>
            </CheckboxGroup>
          </FormItem>
          <FormItem label="备注" prop="remark">
            <Input v-model="form.remark" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="" :disabled="type===0">
            </Input>
          </FormItem>
          <FormItem v-if="this.type===1 || this.type ===2 || this.type===3">
            <Button type="primary" @click="handleSubmit" style="margin-left: 15px;">确定</Button>
            <Button type="primary" @click="handleBack" style="margin-left: 15px;">返回</Button>
            <Button type="warning" @click="cancelFormEdit" style="margin-left: 15px;">取消</Button>
          </FormItem>
          <FormItem v-if="this.type===0">
            <Button type="primary" @click="changeFormEdit" style="margin-left: 15px;">编辑</Button>
            <Button type="error" @click="handleFormDel" style="margin-left: 15px;">删除</Button>
            <Button type="primary" @click="handleBack" style="margin-left: 15px;">返回</Button>
          </FormItem>
        </Form>
      </div>
      </Col>
    </Row>
    <Modal v-model="positionCodeModal" title="请选择岗位" @on-ok="positionOk" @on-cancel="positionCancel">
      <Tree :data="addModalTreeData" @on-select-change="handleSelectAddModalTreeDataChange"></Tree>
    </Modal>
    <Modal v-model="positionCodeTranModal" title="请选择岗位" @on-ok="positionOk" @on-cancel="positionCancel">
      <div class="demo-split">
          <Split v-model="split1">
              <div slot="left" class="demo-split-pane">
                  <Tree :data="tranModalTreeData" @on-select-change="handleTranAddModalTreeDataChange"></Tree>
              </div>
              <div slot="right" class="demo-split-pane">
                  <Tree :data="tranOrgModalTreeData" @on-select-change="handleTranAddModalTreeDataChange"></Tree>
              </div>
          </Split>
      </div>
    </Modal>
  </Card>

</template>

<script>
export default {
  data () {
    const validatePwd = (rule, value, callback) => {
      if (!value || value === null || value === '') {
        callback(new Error('密码不能为空'))
      } else {
        if (this.form.confirmPwd !== '') {
          // 对第二个密码框单独验证
          this.$refs.form.validateField('confirmPwd')
        }
        callback()
      }
    }
    const validateConfirmPwd = (rule, value, callback) => {
      if (value !== this.form.userPwd) {
        callback(new Error('两次密码不一致'))
      } else {
        callback()
      }
    }
    const validateSelectRoles = (rule, value, callback) => {
      value = this.selectRoles
      if (!value || value === null || value.length < 1) {
        callback(new Error('角色不能为空'))
      } else {
        callback()
      }
    }
    return {
      baseUrl: this.$appContext.marvels_core_system,
      split1: 0.5,
      $ajax: null,
      addModalTreeData: [],
      tranModalTreeData: [],
      tranOrgModalTreeData: [],
      treeData: [],
      subVue: '',
      inUserCode: null,
      columns1: [{
        title: '序号',
        type: 'index',
        width: 60,
        align: 'center'
      },
      {
        align: 'center',
        title: '姓名',
        key: 'realName'
      },
      {
        align: 'center',
        title: '用户名',
        key: 'userCode',
        render: function (h, params) {
          const vm = this
          return h('div', {
            on: {
              click () {
                vm.handleView(params)
              }
            },
            style: {
              'color': '#20a0ff',
              'cursor': 'pointer'
            }
          }, params.row.userCode)
        }.bind(this)
      },
      {
        align: 'center',
        title: '手机',
        key: 'mobileNo'
      },
      {
        align: 'center',
        title: '邮箱',
        key: 'email'
      },

      {
        align: 'center',
        title: '座机区号',
        key: 'phoneZoneNo'
      },
      {
        align: 'center',
        title: '座机号',
        key: 'shortPhoneNo'
      },
      {
        align: 'center',
        title: '状态',
        key: 'status',
        render: (h, params) => {
          const vm = this
          return h('div', {
            domProps: {
              innerHTML: vm.renderColumnContext(params)
            }
          }, params.content)
        }
      },
      {
        align: 'center',
        title: '最后更新时间',
        key: 'updatedDate',
        sortable: 'custom',
        sortType: 'desc',
        render: (h, params) => {
          var vm = this
          return h('div', [
            h('span', vm.$util.formatTime(params.row.updatedDate))
          ])
        }

      },
      {
        align: 'center',
        title: '最后更新人员',
        key: 'updatedBy'
      },
      {
        align: 'center',
        title: '操作',
        width: 130,
        key: 'action',
        render: (h, params) => {
          var vm = this
          if (sessionStorage['userCode'] === 'admin') {
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    vm.handleEdit(params)
                  }
                }
              }, ' 编辑'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                on: {
                  click: () => {
                    vm.handleDel(params)
                  }
                }
              }, ' 删除'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                on: {
                  click: () => {
                    vm.handlePassword(params)
                  }
                }
              }, ' 重置密码')
            ])
          }
          return h('div', [
            h('Button', {
              props: {
                type: 'primary',
                size: 'small'
              },
              style: {
                marginRight: '5px'
              },
              on: {
                click: () => {
                  vm.handleEdit(params)
                }
              }
            }, ' 编辑'),
            h('Button', {
              props: {
                type: 'error',
                size: 'small'
              },
              on: {
                click: () => {
                  vm.handleDel(params)
                }
              }
            }, ' 删除')
          ])
        }
      }
      ],
      pageList: {
        data: [],
        dataTotal: 0,
        pageTotal: 1,
        pageNum: 1,
        pageSize: 10,
        sortBy: 'updatedDate',
        sortType: 'desc'
      },
      selectOrgObj: null,
      type: null,
      positionCodeModal: false,
      positionCodeTranModal: false,
      form: {
        userId: null,
        orgCode: null,
        userCode: null,
        userNamep: null,
        userPwd: null,
        confirmPwd: null,
        realName: null,
        idCardNo: null,
        email: null,
        mobileNo: null,
        phoneZoneNo: null,
        shortPhoneNo: null,
        entryDate: null,
        leaveDate: null,
        userPwdValid: null,
        userPwdExpired: null,
        remark: null,
        status: 0,
        positionCode: null,
        positionName: null,
        createdDate: null,
        updatedDate: null,
        createdBy: null,
        updatedBy: null,
        roles: [], // 待传递给后端的用户角色对象数组
        selectRoles: [] // 表单校验使用
      },
      selectRoles: [], // 页面表单勾选的角色字符串数组（form.selectRoles有bug，可能无法获取多个勾选的chebox值）
      rules: {
        userCode: [{
          required: true,
          message: '用户名不能为空',
          trigger: 'blur'
        }],
        userNamep: [{
          required: true,
          message: '昵称不能为空',
          trigger: 'blur'
        }],
        realName: [{
          required: true,
          message: '姓名不能为空',
          trigger: 'blur'
        }],
        idCardNo: [{
          required: true,
          message: '身份证号不能为空',
          trigger: 'blur'
        },
        {
          pattern: this.$util.regExpIdCardNo,
          message: '身份证号格式不正确',
          trigger: 'blur'
        }],
        mobileNo: [{
          required: true,
          message: '手机号码不能为空',
          trigger: 'blur'
        },
        {
          pattern: this.$util.regExpMobile,
          message: '手机号码格式不正确',
          trigger: 'blur'
        }],
        entryDate: [
          {
            required: true,
            message: '入职日期不能为空',
            trigger: 'blur',
            type: 'date'
          }
        ],
        email: [{
          required: true,
          message: '邮箱不能为空',
          trigger: 'blur'
        },
        {
          pattern: this.$util.regExpEmail,
          message: '邮箱格式不正确',
          trigger: 'blur'
        }],
        status: [{
          required: true,
          type: 'number',
          message: '状态不能为空',
          trigger: 'blur'
        }],
        userPwd: [{
          required: true,
          validator: validatePwd,
          // message: "密码不能为空",
          trigger: 'blur'
        }],
        confirmPwd: [{
          required: true,
          validator: validateConfirmPwd,
          // message: "确认密码不能为空",
          trigger: 'blur'
        }],
        selectRoles: [{
          // required: true,
          // type: 'array',
          // min: 1,
          // message: '角色不能为空',
          // trigger: 'change'
          required: true,
          validator: validateSelectRoles,
          trigger: 'blur'
        }]
      },
      roleList: [],
      selectStatus: [{
        value: 0,
        label: '在职'
      },
      {
        value: 1,
        label: '离职'
      }
      ],
      initPwd: '123456',
      choosedRow: null // 列表点击时的行 用户对象
    }
  },
  computed: {

  },
  methods: {
    // 表格单元格渲染布尔值
    renderColumnContext: function (rowContext) {
      if (rowContext.column.key === 'status') {
        return rowContext.row.status === 0 ? '在职' : '离职'
      }
    },
    // 组织机构树节点点击事件
    handleSelectChange (val) {
      this.selectOrgObj = val[0]
      var params = this.initSearchCondition()
      this.searchPage(params)
    },
    handleSelectAddModalTreeDataChange (val) {
      let selectPosition = val[0]
      let positionCode = selectPosition.positionCode
      let positionName = selectPosition.positionName
      this.form.positionName = positionName
      this.form.positionCode = positionCode
    },
    handleTranAddModalTreeDataChange (val) {
      let selectPosition = val[0]
      let positionCode = selectPosition.positionCode
      let positionName = selectPosition.positionName
      this.form.positionName = positionName
      this.form.positionCode = positionCode
    },
    // 转岗模态框加载
    selectTraPosition () {
      this.positionCodeTranModal = true
    },
    // 选择岗位模态框加载
    selectPosition () {
      this.positionCodeModal = true
      let vm = this
      var url = this.baseUrl + 'system/pmsn/service/getPositionTreeByOrgCode'
      let params = {}
      params.orgCode = this.selectOrgObj.orgCode
      this.$ajax.post(url, params).then(re => {
        var data = re.data
        let arr = data.data
        if (arr.length > 0) {
          for (let i = 0; i < arr.length; i++) {
            let temArr = arr[i]
            vm.selectOpstionItem(temArr)
          }
        }
        vm.addModalTreeData = data.data
      }).catch(er => {
        this.$Message.error(er)
      })
    },
    selectOpstionItem (data) {
      data.title = data.positionName
      let arr = data.children
      if (arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
          let temArr = arr[i]
          this.selectOpstionItem(temArr)
        }
      }
    },
    positionCancel () {

    },
    positionOk () {

    },
    // 初始化列表查询条件
    initSearchCondition () {
      this.subVue = 'view'
      this.inUserCode = null
      var params = {
        pageNo: 1,
        pageSize: this.pageList.pageSize,
        param: {
          orgCode: this.selectOrgObj.orgCode,
          sortBy: this.pageList.sortBy,
          sortType: this.pageList.sortType
        }
      }
      return params
    },
    // 分页查询
    searchPage (initParam) {
      var params = {
        pageNo: this.pageList.pageNum,
        pageSize: this.pageList.pageSize,
        param: {
          orgCode: this.selectOrgObj.orgCode,
          userCode: this.inUserCode,
          sortBy: this.pageList.sortBy,
          sortType: this.pageList.sortType
        }
      }
      if (initParam) {
        params = initParam
      }
      var url = this.baseUrl + 'system/pmsn/service/userPageListByOrgCode/' + params.pageNo + '/' + params.pageSize
      this.$ajax.post(url, params.param).then(re => {
        var data = re.data
        var code = data.code
        var message = data.message
        if (code !== 'success') {
          this.$Message.warning(message)
          return
        }
        this.pageList.data = data.data.list
        this.pageList.pageTotal = data.data.pages
        this.pageList.dataTotal = data.data.total
      }).catch(er => {

      })
    },
    initpage: function () {
      var vm = this
      this.$ajax.post(this.baseUrl + 'system/pmsn/service/getOrgTree').then(re => {
        var data = re.data
        var code = data.code
        var message = data.message
        if (code !== 'success') {
          this.$Message.warning(message)
          return
        }
        vm.treeData = vm.toTree(data.data)
      }).catch(er => {

      })
    },
    toTree: function (data) {
      var vm = this
      if (data && data.length > 0) {
        for (var index in data) {
          var onedata = data[index]
          data[index].title = onedata.orgName
          if (data[index].children && data[index].children.length > 0) {
            vm.toTree(data[index].children)
          }
        }
      }
      return data
    },
    // 查询列表排序
    sortChange: function (column, key, order) {
      if (column.order !== 'normal') {
        this.pageList.sortBy = column.key
        this.pageList.sortType = column.order
        this.searchPage()
      }
    },
    // 查询列表翻页
    handlePageChange (index) {
      this.pageList.pageNum = index
      this.searchPage()
    },
    // 用户列表行删除按钮
    handleDel (rowContext) {
      this.choosedRow = rowContext.row
      this.handleFormDel()
    },
    // 表单页面删除按钮
    handleFormDel () {
      var config = {
        title: '提示',
        content: '是否确认删除?',
        onOk: this.deleteUser
      }
      this.$Modal.confirm(config)
    },
    // 删除用户
    deleteUser () {
      var vm = this
      var params = {
        userId: this.choosedRow.userId,
        userCode: this.choosedRow.userCode
      }
      this.$ajax.post(this.baseUrl + 'system/pmsn/service/delUser', params).then(re => {
        var data = re.data
        var code = data.code
        var message = data.message
        if (code !== 'success') {
          this.$Message.warning(message)
          return
        }
        if (vm.type === 0) {
          vm.subVue = 'view'
          vm.type = null
        }
        vm.searchPage()
      }).catch(er => {

      })
    },
    // 打开用户新增页面
    handleAdd () {
      this.type = 2
      this.subVue = 'edit'
      this.form = {
        status: 0
      }
      this.getRoleList()
    },
    // 表单确认按钮事件
    handleSubmit () {
      var vm = this
      this.$refs.form.validate(valid => {
        if (valid) {
          var config = {
            title: '提示'
          }
          if (this.type === 1) {
            config.content = '是否确认修改?'
            config.onOk = vm.updateUser
          } else if (this.type === 2) {
            config.content = '是否确认新建?'
            config.onOk = vm.addUser
          }
          vm.$Modal.confirm(config)
        }
      })
    },
    handleBack () {
      this.subVue = 'view'
      this.type = null
      this.searchPage()
    },
    // 打开用户编辑页面
    handleEdit (rowContext) {
      this.type = 1
      this.subVue = 'edit'
      this.choosedRow = rowContext.row
      this.getRoleList()
    },
    showUserInfo () {
      var vm = this
      var params = {
        userId: this.choosedRow.userId
      }
      this.$ajax.post(this.baseUrl + 'system/pmsn/service/userDetail', params).then(re => {
        var data = re.data
        var code = data.code
        var message = data.message
        if (code !== 'success') {
          this.$Message.warning(message)
          return
        }
        vm.form = data.data
        var ary = vm.form.roles
        if (vm.form.entryDate) {
          vm.form.entryDate = vm.$util.formatDate(vm.form.entryDate)
        }
        if (vm.form.leaveDate) {
          vm.form.leaveDate = vm.$util.formatDate(vm.form.leaveDate)
        }
        vm.selectRoles = []
        if (ary && ary.length > 0) {
          for (var i in ary) {
            if (ary[i].roleCode && ary[i].roleCode != null && ary[i].roleCode !== '') {
              vm.selectRoles.push(ary[i].roleCode)
            }
          }
        }
      }).catch(er => {

      })
    },
    // 获取系统全部角色
    getRoleList: function () {
      var vm = this
      this.$ajax.post(this.baseUrl + 'system/pmsn/service/roleAll').then(re => {
        var data = re.data
        var code = data.code
        var message = data.message
        if (code !== 'success') {
          this.$Message.warning(message)
          return
        }
        this.roleList = data.data
        if (this.type === 1 || this.type === 0) {
          vm.showUserInfo()
        }
      }).catch(er => {

      })
    },
    // 新增用户
    addUser () {
      this.form.orgCode = this.selectOrgObj.orgCode
      this.form.roles = this.handleChoosedRolesData()
      var params = this.form
      this.$ajax.post(this.baseUrl + 'system/pmsn/service/addUser', params).then(re => {
        var data = re.data
        var code = data.code
        var message = data.message
        if (code !== 'success') {
          this.$Message.warning(message)
          return
        }
        var params = this.initSearchCondition()
        this.searchPage(params)
      }).catch(er => {

      })
    },
    // 将选中的角色字符串数组转换成角色对象数组
    handleChoosedRolesData: function () {
      var userCode = this.form.userCode
      var roles = []
      for (var i in this.selectRoles) {
        var role = this.selectRoles[i]
        roles.push({
          userCode: userCode,
          roleCode: role
        })
      }
      return roles
    },
    // 更新用户
    updateUser () {
      this.form.orgCode = this.selectOrgObj.orgCode
      this.form.roles = this.handleChoosedRolesData()
      var params = this.form
      this.$ajax.post(this.baseUrl + 'system/pmsn/service/updateUser', params).then(re => {
        var data = re.data
        var code = data.code
        var message = data.message
        if (code !== 'success') {
          this.$Message.warning(message)
          return
        }
        var params = this.initSearchCondition()
        this.searchPage(params)
      }).catch(er => {

      })
    },
    // 查看用户详情
    handleView (rowContext) {
      this.type = 0
      this.subVue = 'edit'
      this.choosedRow = rowContext.row
      this.getRoleList()
    },
    // 变更表单只读为编辑状态
    changeFormEdit () {
      this.type = 1
    },
    // 取消表单编辑状态
    cancelFormEdit () {
      this.type = 0
    },
    handlePassword (params) {
      var config = {
        title: '提示',
        content: '确定重置该用户的密码为 ' + this.initPwd + ' ?',
        onOk: () => {
          this.initPassword(params)
        }
      }
      this.$Modal.confirm(config)
    },
    initPassword (params) {
      var request = {}
      request.userId = params.row.userId
      request.userPwd = this.initPwd
      this.$ajax.post(this.baseUrl + 'system/service/initPassword', request).then(re => {
        var data = re.data
        var code = data.code
        var message = data.message
        if (code !== 'success') {
          this.$Message.warning(message)
          return
        }
        this.$Message.success(message)
      }).catch(er => {

      })
    }
  },
  mounted () {
    this.$ajax = this.$util.ajax()
    this.initpage()
  },
  created: function () {

  }
}
</script>
